package com.example.dangerouscargodriver.controller;

import android.content.Context;
import android.os.Message;
import android.util.Log;

import com.baiju.netmanager.Http.HttpRequest;
import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.netmanager.Http.INetResponse;
import com.example.dangerouscargodriver.DangerousCargoDriverApplication;
import com.example.dangerouscargodriver.entry.ResourceTypeInfo3;
import com.example.dangerouscargodriver.entry.ResourceTypeInfo2;
import com.example.dangerouscargodriver.entry.TruckLengthInfo;
import com.example.dangerouscargodriver.entry.TruckTypeInfo;
import com.example.dangerouscargodriver.event.Event;
import com.example.dangerouscargodriver.event.LoadHttpResourceStatus;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

public class AttrInfoController extends Controller{

    private static final String TAG = "AttrInfoController";
    private static AttrInfoController mInstance = null;

    public static final int EVENT_ATTR_LOADING = 0;
    public static final int EVENT_ATTR_LOAD_DONE = 1;

    private static final int MSG_LOAD_ATTR_CORE_DONE = 0;
    private static final  int MSG_ADD_LISTENER = 1;
    private static final int MSG_LOAD_ATTR_TRUCK_CLASS_DONE = 2;
    private static final int MSG_LOAD_ATTR_CORE_3_DONE = 3;
    private static final int MSG_EXECUTE_LOAD_ATTR_CORE = 4;
    private static final int MSG_EXECUTE_LOAD_ATTR_TRUCK_CLASS = 5;
    private static final int MSG_EXECUTE_LOAD_ATTR_CORE_3 = 6;

    private static final int CORE_ATTR_LITTLE = 1;

    private int mLoadHttpStatus = EVENT_ATTR_LOADING;

    private HttpRequest mHttp = null;
    private HttpResponseListener mHttpListener = null;

    private List<ResourceTypeInfo2> mResourceTypeArray = null;
    private List<ResourceTypeInfo3> mResourceTypeArray3 = null;
    private boolean mLoadResourceType = false;
    private boolean mLoadResourceType3 = false;

    private List<TruckTypeInfo> mTruckTypeArray = null;
    private boolean mLoadTruckType = false;

    private List<TruckLengthInfo> mTruckLengthArray = null;

    private HashMap<java.lang.Class, IControllerEventListener> mControllerListener = null;

    public static AttrInfoController Instance(){
        if(mInstance == null){
            mInstance = new AttrInfoController(DangerousCargoDriverApplication.getAppContext());
        }

        return mInstance;
    }

    public AttrInfoController(Context context){
        mHttpListener = new HttpResponseListener();
        mControllerListener = new HashMap<>();
        mHttp = HttpRequest.Instance(context);
        mHttp.attachResponseListener(mHttpListener, AttrInfoController.class);
        mHttp.startUp();

        loadCoreAttrInfo();
        loadCoreAttr3Info();
        loadTruckClassInfo();
    }

    public boolean attachControllerListener(java.lang.Class object, IControllerEventListener listener){
        if(mControllerListener.containsKey(object)){
            return false;
        }
        else {
            mControllerListener.put(object, listener);
            Message msg = new Message();
            msg.what = MSG_ADD_LISTENER;
            msg.obj = object;
            sendMessage(msg);

            return true;
        }
    }

    public boolean unAttachControllerListener(java.lang.Class object, IControllerEventListener listener){
        if(mControllerListener.containsKey(object) && mControllerListener.get(object) == listener){
            mControllerListener.remove(object);
            return true;
        }
        else {
            return false;
        }
    }

    public List<TruckTypeInfo> getTruckTypeArray() {
        return mTruckTypeArray;
    }

    public List<ResourceTypeInfo2> getResourceTypeArray() {
        return mResourceTypeArray;
    }

    public List<ResourceTypeInfo3> getResourceTypeArray3() {
        return mResourceTypeArray3;
    }

    private void loadCoreAttrInfo(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("app-type", "Android");

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("core_attr", "2");

        mHttp.sendRequest(
                IHttpRequest.RequestMethod.GET_METHOD,
                RemoteAPI.REQUEST_V1_HOME_ATTR_LIST,
                header,
                param,
                RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_CORE_ATTR,
                AttrInfoController.class);
    }

    private void loadCoreAttr3Info(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("app-type", "Android");

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("core_attr", "3");
        mHttp.sendRequest(
                IHttpRequest.RequestMethod.GET_METHOD,
                RemoteAPI.REQUEST_V1_HOME_ATTR_LIST,
                header,
                param,
                RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_CORE_ATTR + CORE_ATTR_LITTLE,
                AttrInfoController.class);
    }

    private void loadTruckClassInfo(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("app-type", "Android");

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("truck_class", "2");
        mHttp.sendRequest(
                IHttpRequest.RequestMethod.GET_METHOD,
                RemoteAPI.REQUEST_V1_HOME_ATTR_LIST,
                header,
                param,
                RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_TRUCK_CLASS,
                AttrInfoController.class);
    }

    private boolean checkLoadComplete(){
        return mLoadTruckType && mLoadResourceType && mLoadResourceType3;
    }

    @Override
    public void handleControllerMessage(Message msg){
        switch (msg.what){
            case MSG_LOAD_ATTR_CORE_DONE:
                mLoadResourceType = true;
                if (checkLoadComplete()) {
                    mLoadHttpStatus = EVENT_ATTR_LOAD_DONE;
                    LoadHttpResourceStatus status = new LoadHttpResourceStatus();
                    status.setWhat(mLoadHttpStatus);
                    for (java.lang.Class key : mControllerListener.keySet()) {
                        mControllerListener.get(key).onEvent(Event.EVENT_LOAD_HTTP_RESOURCE_CORE_ATTR, status.toJson());
                    }
                }
                break;
            case MSG_EXECUTE_LOAD_ATTR_CORE:
                loadCoreAttrInfo();
                break;
            case MSG_LOAD_ATTR_TRUCK_CLASS_DONE:
                mLoadTruckType = true;
                if (checkLoadComplete()) {
                    mLoadHttpStatus = EVENT_ATTR_LOAD_DONE;
                    LoadHttpResourceStatus status = new LoadHttpResourceStatus();
                    status.setWhat(mLoadHttpStatus);
                    for (java.lang.Class key : mControllerListener.keySet()) {
                        mControllerListener.get(key).onEvent(Event.EVENT_LOAD_HTTP_RESOURCE_CORE_ATTR, status.toJson());
                    }
                }
                break;
            case MSG_EXECUTE_LOAD_ATTR_TRUCK_CLASS:
                loadTruckClassInfo();
                break;
            case MSG_LOAD_ATTR_CORE_3_DONE:
                mLoadResourceType3 = true;
                if (checkLoadComplete()) {
                    mLoadHttpStatus = EVENT_ATTR_LOAD_DONE;
                    LoadHttpResourceStatus status = new LoadHttpResourceStatus();
                    status.setWhat(mLoadHttpStatus);
                    for (java.lang.Class key : mControllerListener.keySet()) {
                        mControllerListener.get(key).onEvent(Event.EVENT_LOAD_HTTP_RESOURCE_CORE_ATTR, status.toJson());
                    }
                }
                break;
            case MSG_EXECUTE_LOAD_ATTR_CORE_3:
                loadCoreAttr3Info();
                break;
            case MSG_ADD_LISTENER:
                LoadHttpResourceStatus status = new LoadHttpResourceStatus();
                status.setWhat(mLoadHttpStatus);
                mControllerListener.get(msg.obj).onEvent(Event.EVENT_LOAD_HTTP_RESOURCE_CORE_ATTR, status.toJson());
                break;
            default:
                break;
        }
    }

    private class HttpResponseListener implements INetResponse {

        private static final String TAG = "HttpResponseListener";

        @Override
        public void onResponse(int actionId, String response) {
            try {
                JSONObject res = new JSONObject(response);
                Gson gson = new Gson();
                if(actionId == RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_CORE_ATTR){
                    //Log.d(TAG, "onResponse: " + response);
                    ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                    if(responseInfo != null && responseInfo.getStatus() == 1){
                        if(res.getJSONObject("data").has("core_attr")) {
                            JSONArray data = res.getJSONObject("data").getJSONArray("core_attr");
                            Type type = new TypeToken<List<ResourceTypeInfo2>>() {}.getType();
                            mResourceTypeArray = gson.fromJson(data.toString(), type);
                        }
                        else{

                        }

                        Message msg = new Message();
                        msg.what = MSG_LOAD_ATTR_CORE_DONE;
                        sendMessage(msg);
                    }
                    else{
                        //返回异常
                        Message message = new Message();
                        message.what = MSG_EXECUTE_LOAD_ATTR_CORE;
                        sendMessage(message);
                    }
                }
                else if(actionId == RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_CORE_ATTR + CORE_ATTR_LITTLE){
                    //Log.d(TAG, "onResponse: " + response);
                    ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                    if(responseInfo != null && responseInfo.getStatus() == 1){
                        if(res.getJSONObject("data").has("core_attr")) {
                            JSONArray data = res.getJSONObject("data").getJSONArray("core_attr");
                            Type type = new TypeToken<List<ResourceTypeInfo3>>() {}.getType();
                            mResourceTypeArray3 = gson.fromJson(data.toString(), type);
                        }
                        else{

                        }
                        Message msg = new Message();
                        msg.what = MSG_LOAD_ATTR_CORE_3_DONE;
                        sendMessage(msg);
                    }
                    else{
                        //返回异常
                        Message message = new Message();
                        message.what = MSG_EXECUTE_LOAD_ATTR_CORE_3;
                        sendMessage(message);
                    }
                }
                else if(actionId == RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_TRUCK_CLASS){
                    //Log.d(TAG, "onResponse: " + response);
                    ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                    if(responseInfo != null && responseInfo.getStatus() == 1){
                        if(res.getJSONObject("data").has("truck_class")) {
                            JSONArray data = res.getJSONObject("data").getJSONArray("truck_class");
                            Type type = new TypeToken<List<TruckTypeInfo>>() {}.getType();
                            mTruckTypeArray = gson.fromJson(data.toString(), type);
                        }
                        else{

                        }
                        Message msg = new Message();
                        msg.what = MSG_LOAD_ATTR_TRUCK_CLASS_DONE;
                        sendMessage(msg);
                    }
                    else{
                        //返回异常
                        Message message = new Message();
                        message.what = MSG_EXECUTE_LOAD_ATTR_TRUCK_CLASS;
                        sendMessage(message);
                    }
                }
                else if(actionId == RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_TRUCK_LENGTH){
                    Log.d(TAG, "onResponse: " + response);
                    ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                    if(responseInfo != null && responseInfo.getStatus() == 1){
                        if(res.getJSONObject("data").has("truck_length")) {
                            JSONArray data = res.getJSONObject("data").getJSONArray("truck_length");
                            Type type = new TypeToken<List<TruckLengthInfo>>() {}.getType();
                            mTruckLengthArray = gson.fromJson(data.toString(), type);
                        }
                        else{

                        }
                    }
                }
                else{

                }
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onErrorResponse(int actionId, String response) {
            if(actionId == RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_CORE_ATTR){
                loadCoreAttrInfo();
            }
            else if(actionId == RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_CORE_ATTR + CORE_ATTR_LITTLE){
                loadCoreAttr3Info();
            }
            else if(actionId == RemoteAPICmd.REQUEST_V1_HOME_ATTR_LIST_TRUCK_LENGTH){
                loadTruckClassInfo();
            }
        }
    }
}
